﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Net
{
    public class Serializer
    {
        public void Serialize(ref byte[] buffer, object data)
        {
            Type type = data.GetType();
        }


        public static byte[] ToBinary(object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(ms, obj);

                byte[] resbytes = new byte[ms.Length];

                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(resbytes, 0, (int)ms.Length);

                return resbytes;
            }
        }

        public static object FromBinary(byte[] data)
        {
            object obj = null;
            using (MemoryStream ms = new MemoryStream(data))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                try
                {
                    obj = binaryFormatter.Deserialize(ms);
                }
                catch (Exception ex)
                {
                }
            }
            return obj;
        }

        public static NetPackage ToNetBuffer(object obj, byte command, byte replyMode, uint clientID)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(ms, obj);

                NetPackage buffer = new NetPackage(command, replyMode, clientID, ms);

                return buffer;
            }
        }

        public static object FromNetBuffer(NetPackage buffer)
        {
            object obj = null;
            using (MemoryStream ms = new MemoryStream(buffer.Buffer, NetPackage.HeaderLength, (int)buffer.DataLength))
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();

                try
                {
                    obj = binaryFormatter.Deserialize(ms);
                }
                catch (Exception ex)
                {
                }
            }
            return obj;
        }
    }
}
